<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/11
 * Time: 11:01
 */
namespace app\index\model;
use think\Controller;
use think\Model;
use think\Db;
use app\api\model\Hotel;
use app\api\model\Tour;
use app\common\model\AppraiseModel;

class Collect extends Model
{
    /**
     *我的收藏
     */
    public function collects($uid,$type)
    {

        //查询好评率
        $Appraise = new AppraiseModel();
        if($type==1){
            $list = Db::name('collect')->alias('c')->join('tours t','c.other_id=t.tour_id','LEFT')
                ->field('t.tour_id,t.tour_name,t.tour_covers,t.tour_tag,t.sale_sum')
                ->where('c.uid',$uid)
                ->where('c.type',1)
                ->order('c.create_time','desc')
                ->select();
            if(!empty($list)){
                foreach ($list as $k=>$v){

                    //查询最低价格
                    $ticket = Db::name('tour_ticket')
                        ->field('price,discount_price,is_discount')
                        ->where('is_del',0)
                        ->where('is_use',1)
                        ->where('tour_id',$v['tour_id'])
                        ->select();

                    if (empty($ticket)){
                        $list[$k]['minprice'] = '暂无';
                    }else{

                        foreach ($ticket as $k2 => $v2){

                            if ($v2['is_discount']){

                                $minPrice[] = $v2['discount_price']*1;

                            }else{

                                $minPrice[] = $v2['price']*1;

                            }

                        }

                        if (count($minPrice)>1){
                            $list[$k]['minprice'] = min($minPrice);
                        }else{
                            $list[$k]['minprice'] = $minPrice[0];
                        }

                    }

                    //标签转数组
                    $list[$k]['tour_tag'] = explode(',',$v['tour_tag']);


                    $list[$k]['rate'] = $Appraise->getAppRate(2,$v['tour_id']);

                    //查询前三张图
                    $list[$k]['img'] = Db::name('tour_img')->field('img_path')->where('tour_id',$v['tour_id'])->order('sort','desc')->limit(0,3)->select();


                }
            }

            return $list;
        }

        if($type==2){

            $list = Db::name('collect')->alias('c')->join('hotel h','c.other_id=h.hotel_id','LEFT')
                ->field('hotel_id,hotel_name,hotel_covers,hotel_tag,sum_sale')
                ->where('c.uid',$uid)
                ->where('c.type',2)
                ->order('c.create_time','desc')
                ->select();

            if(!empty($list)) {
                foreach ($list as $k2 => $v2){

                    //查询最低价格
                    $room = Db::name('hotel_room')
                        ->field('room_price,room_discount_price,is_tehui')
                        ->where('is_del',0)
                        ->where('is_display',0)
                        ->where('hotel_id',$v2['hotel_id'])
                        ->select();

                    if (empty($room)){
                        $list[$k2]['minprice'] = '暂无';
                    }else{

                        foreach ($room as $k22 => $v22){

                            if ($v22['is_tehui']){

                                $minPrice[] = $v22['room_discount_price']*1;

                            }else{

                                $minPrice[] = $v22['room_price']*1;

                            }

                        }

                        if (count($minPrice)>1){
                            $list[$k2]['minprice'] = min($minPrice);
                        }else{
                            $list[$k2]['minprice'] = $minPrice[0];
                        }

                    }

                    //标签转数组
                    $list[$k2]['hotel_tag'] = explode(',',$v2['hotel_tag']);

                    //查询好评率
                    $list[$k2]['rate'] = $Appraise->getAppRate(1,$v2['hotel_id']);
                }
            }
            return $list;
        }

        if($type==3){
            $res = Db::name('collect')->alias('c')->join('group_tour g','c.other_id=g.id','LEFT')
                ->field('id,gtour_covers,gtour_days,gtour_title,gtour_label,gtour_price,sale_sum')
                ->where('c.uid',$uid)
                ->where('c.type',3)
                ->order('c.create_time','desc')
                ->select();
            return $res;
        }

        if($type==4){
            $res = Db::name('collect')->alias('c')->join('food_store f','c.other_id=f.food_store_id','LEFT')
                ->field('food_store_id,food_store_name,food_store_cover,food_people_money,food_tag')
                ->where('c.uid',$uid)
                ->where('c.type',4)
                ->order('c.create_time','desc')
                ->select();

            foreach($res as $k => $v){

                $res[$k]['food_tag'] = explode(',',$v['food_tag']);

            }

            return $res;
        }

        if($type==5){
            $res = Db::name('collect')
                ->alias('c')
                ->join('method m','c.other_id=m.mid',"left")
                ->join('user u','m.uid=u.uid','left')
                ->field('m.*,u.user_icon,u.nickname')
                ->where('c.uid',$uid)
                ->where('c.type',5)
                ->order('c.create_time','desc')
                ->select();
            if(!empty($res)){
                foreach($res as $k=>$v){
                    $res[$k]['id'] = $v['mid'];
                    $res[$k]['title'] = $v['title'];

                    $titleCount = self::utf8_strlen($v['title']);
                    $res[$k]['title'] = $titleCount>30?mb_substr($v['title'],0,30).'...':$v['title'];

                    $image = explode(',',$v['image']);
                    $res[$k]['image'] = $image[0];

                    $content = json_decode($v['content'],true);
                    $res[$k]['content'] = json_decode($v['content'],true);

                    $content_str = '';
                    foreach ($content as $k2 => $v2){
                        $content_str .= $v2['data'];
                    }
                    $res[$k]['content'] = mb_substr($content_str,0,45);
                    $res[$k]['content'] .= '...';

                    $res[$k]['like_num'] = $v['like_num']*1 + $v['set_like_num']*1;
                    $res[$k]['read_num'] = $v['read_num']*1 + $v['set_read_num']*1;
                    $res[$k]['share_num'] = $v['set_share_num']*1 + $v['share_num']*1;

                    $res[$k]['is_video'] = 0;
                    $res[$k]['is_method'] = 1;
                    $res[$k]['nickname'] = $v['nickname'];
                    $res[$k]['user_icon'] = $v['user_icon'];
                    $res[$k]['time'] = time_ago($v['create_time']);
                }
            }
            return $res;
        }

        if($type==6){
            $res = Db::name('collect')->alias('c')->join('friends_circle m','c.other_id=m.f_id','left')
                ->join('user u','m.uid = u.uid','left')
                ->field('m.*,u.user_icon,u.nickname')
                ->where('c.uid',$uid)
                ->where('c.type',6)
                ->order('c.create_time','desc')
                ->select();
            if(!empty($res))
            {
                foreach ($res as $k0 => $v0) {
                    $res[$k0]['id'] = $v0['f_id'];
                    $titleCount = self::utf8_strlen($v0['fc_title']);
                    $res[$k0]['title'] = $titleCount>30?mb_substr($v0['fc_title'],0,30).'...':$v0['fc_title'];

                    if ($v0['status'] == 1){

                        $image = explode(',',$v0['image']);
                        $res[$k0]['image'] = $image[0];

                        $res[$k0]['content'] = mb_substr($v0['content'],0,45);


                    }else{

                        $res[$k0]['image'] = $v0['video']."?vframe/jpg/offset/1";
                        $res[$k0]['content'] = mb_substr($v0['video_content'],0,45);

                    }

                    $res[$k0]['like_num'] = $v0['like_num']*1 + $v0['set_like_num']*1;
                    $res[$k0]['read_num'] = $v0['read_num']*1 + $v0['set_read_num']*1;
                    $res[$k0]['share_num'] = $v0['set_share_num']*1 + $v0['share_num']*1;

                    $res[$k0]['is_video'] = $v0['status']==2?1:0;
                    $res[$k0]['is_method'] = 0;

                    $res[$k0]['nickname'] = $v0['nickname'];
                    $res[$k0]['user_icon'] = $v0['user_icon'];
                    $res[$k0]['time'] = time_ago($v0['create_time']);
                }
            }
            return $res;
        }

    }

   /**
    * [addCollection 添加收藏]
    * @Author   kendy
    * @DateTime 2019-11-14T14:09:25+0800
    */
    public function addCollection()
    {

          $userId = input('post.user_id/d');

          if(empty($userId))
             return apiReturn('400','用户信息为空',0);
          $otherId = input('post.other_id/d');
          if(empty($otherId))
             return apiReturn('400','产品id为空',0);
         $type = input('post.type/d');
          if(empty($type))
             return apiReturn('400','产品类型为空',0);
           
        $data['uid'] = $userId;
        $data['other_id'] = $otherId;
        $data['type'] = $type;
        $is_collect = Db::name('collect')->where($data)->find();
        if($is_collect)
          return apiReturn('200','收藏成功',0); 
        $data['create_time'] = date('Y-m-d H:i:s',time()); 
        if(in_array($type, [1,2,3,4,5,6]))
        {  
          //攻略
          if($type==5)
          {
            $collect = Db::name('method')
            ->where(['mid'=>$data['other_id'],'is_pass'=>1,'is_del'=>0,'is_display'=>0])
            ->find();
            if(empty($collect))
            return apiReturn('400','无效的攻略信息',0);
            Db::name('method')->where('mid',$otherId)->setInc('collect_num',1); 
          }
          //友圈
          if($type==6)
          {
             $collect = Db::name('friends_circle')
             ->where(['f_id'=>$otherId,'is_pass'=>1,'is_del'=>0,'is_display'=>0])
             ->find();
             if(empty($collect))
             return apiReturn('400','无效的友圈信息',0);
             Db::name('friends_circle')->where('f_id',$otherId)->setInc('collect_num',1);
          }
          //判断是否有该景点信息
          if($type==1)
          {
             $collect = Db::name('tours')
             ->where(['tour_id'=>$otherId,'is_del'=>0,'is_display'=>0,'is_pass'=>1])
             ->find();
             if(empty($collect))
             return apiReturn('400','无效的景点信息',0);

          }
          //判断是否有该酒店信息
          if($type==2)
          {
            $collect = Db::name('hotel')
            ->where(['hotel_id'=>$otherId,'is_del'=>0,'is_pass'=>1])
            ->find();
            if(empty($collect))
            return apiReturn('400','无效的酒店信息',0);
          }
          //判断是否有该跟团产品
          if($type==3)
          {
            $collect = Db::name('group_tour')
            ->where(['id'=>$otherId,'is_del'=>0,'is_display'=>0])
            ->find();
            if(empty($collect))
            return apiReturn('400','无效的跟团信息',0);
          }
           //判断是否有该美食店铺
          if($type==4)
          {
            $collect = Db::name('food_store')
            ->where(['food_store_id'=>$otherId,'is_del'=>0,'is_pass'=>1])
            ->find();
            if(empty($collect))
            return apiReturn('400','无效的美食店铺信息',0);
          }
          //添加到收藏表
            $rs = Db::name('collect')
            ->insert($data);
            if(false !==$rs){
                return apiReturn('200','收藏成功',0);    
            }
          return apiReturn('200','收藏失败',0);    
   }
}


   /**
    * [getProCollectionnNum 查看产品的收藏数量]
    * @Author   kendy
    * @DateTime 2019-11-15T09:48:05+0800
    * @param    [type]                   $otherId [景点/酒店/跟团/美食/攻略/导游 ID]
    * @param    [type]                   $type    [1景点，2酒店，3跟团，4美食，5攻略，6导游]
    * @return   [type]                            [description]
    */
   public function getProCollectionnNum($otherId,$type)
   {
         return Db::name('collect')
         ->where(['other_id'=>$otherId,'type'=>$type])
         ->count(); 

   }
    
    
    /**
     * [cancelCollection 取消收藏]
     * @Author   kendy
     * @DateTime 2019-12-11T15:53:54+0800
     * @return   [type]                   [description]
     */
    public function cancelCollection()
    {
         $userId = input('post.user_id/d');
          if(empty($userId))
             return apiReturn('400','用户信息为空',0);
          $otherId = input('post.other_id/d');
          if(empty($otherId))
             return apiReturn('400','产品id为空',0);
         $type = input('post.type/d');
          if(empty($type))
             return apiReturn('400','产品类型为空',0);
          $data['uid'] = $userId;
          $data['other_id'] = $otherId;
          $data['type'] = $type;
        $info = Db::name('collect')
        ->where($data)
        ->delete();
        if(false !== $info)
        {
            return apiReturn('200','取消收藏成功',0);
        }
        return apiReturn('400','取消收藏失败',0);
    }

    private function utf8_strlen($string = null) {
        preg_match_all('/./us', $string, $match);
        return count($match[0]);
    }
}